﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DocManagerORM.ORM;
using System.ComponentModel;

namespace DocManagerControls.Controls
{
    /// <summary>
    /// Logica di interazione per CreaWFControl.xaml
    /// </summary>
    public partial class CreaWFControl : BaseCusControl
    {

        NewTaskPageFunc m_NewTaskPageFunc = null;// new Lazy<NewTaskPageFunc>(() => { return new NewTaskPageFunc(); });
        int m_IDdoc = 0;
        string m_FileName = string.Empty;
        int m_Contatore = 0;

        NavigationService m_NavService = null;
        BindingList<Iters> m_ItersList = new BindingList<Iters>();

        QueryIters m_QueryIters = new QueryIters(); 

        public CreaWFControl():base()
        {
            InitializeComponent();
            
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            addMenu();

            txtMittente.Text = GLOBALcontrols.UserName;

            if (DatiGlobaliControlli.getUtenteDati()  == null)
            {
                Logga("Manca l'assegnazione utente",  System.Diagnostics.TraceEventType.Error);
                MessageBox.Show("Assegnare utente : errore critico !");
                return;
            }
            txtGuidMittente.Text = GLOBALcontrols.UtenteDati.UserId.ToString(); 
        }

        private void addMenu()
        {
            MenuItem menu = new MenuItem() {
                Header ="Vedi workflows" 
            };
            addMenuItemsToMenu(new []{ menu});
            
            addMenuHandlerToMenu((e) =>
            {
                switch (e)
                {
                    case "vedi workflows":
                        MessageBox.Show("vedi workflows");
                        caricaWorkflowEsistenti(null, false);
                        break;
                }

                ;
            }); 
        }

        public void caricaWorkflowEsistenti(int? pID,bool pIncludeIters)
        {
            var res = m_QueryIters.getItersManager(pID, pIncludeIters).ToList();

            this.lstIters.ItemsSource = null;
            this.lstIters.ItemsSource = res[0].Iters;

            this.listWorkfEsistenti.ItemsSource =  res;

        }

        public CreaWFControl(int pIDdoc,string pFileName):this()
        {
            
            m_IDdoc = pIDdoc;
            this.txtIDdoc.Text = pIDdoc.ToString();
            m_FileName = pFileName;
            txtFileName.Text = pFileName;

            m_ItersList.AllowNew = true;
            m_ItersList.AllowRemove = true;
            m_ItersList.AllowEdit = true;
            m_ItersList.ListChanged += (oo, ev) => 
            {
                //lstIters.ItemsSource = m_ItersList;                
            };

            lstIters.ItemsSource = m_ItersList;
        }

        private void txtIDdoc_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !AreAllValidNumericChars(e.Text);
            base.OnPreviewTextInput(e);

        }//fM

        private bool AreAllValidNumericChars(string str)
        {
            foreach (char c in str)
            {
                if (!Char.IsNumber(c)) return false;
            }

            return true;
        }//fM

        private void btnAddPassaggio_Click(object sender, RoutedEventArgs e)
        {
            if(m_NavService == null)
                m_NavService = NavigationService.GetNavigationService(this.btnAddPassaggio);

            if (m_NavService != null)
            {
                m_NewTaskPageFunc = new NewTaskPageFunc(m_IDdoc,m_FileName);
                m_NewTaskPageFunc.RemoveFromJournal = true;
                m_NewTaskPageFunc.Return += new ReturnEventHandler<Iters>(Value_Return);
                m_NavService.Navigate(m_NewTaskPageFunc);
            }

        }//fM


        private void updateIter(Iters pIter)
        {
            if (pIter == null) return;

            if (m_NavService != null)
            {
                m_NewTaskPageFunc = new NewTaskPageFunc(pIter, m_FileName);
                m_NewTaskPageFunc.RemoveFromJournal = true;
                m_NewTaskPageFunc.Return += new ReturnEventHandler<Iters>(Value_Return);
                m_NavService.Navigate(m_NewTaskPageFunc);
            }
        
        }//fM

        void Value_Return(object sender, ReturnEventArgs<Iters> e)
        {
            if (e == null) return;
            var retData = e.Result as Iters;
                         
            if (retData == null) return;

            if (retData.ID < 1)
            {
                retData.ID = ++m_Contatore; //nuova
                m_ItersList.Add(retData);
            }
            else
            {
                var item = m_ItersList.Where(x => x.ID == retData.ID).FirstOrDefault();  
                if(item != null)   
                {
                    item.Messaggio = retData.Messaggio;
                    item.Destinatario = retData.Destinatario;
                    item.Fk_IDUser_Destinatario = retData.Fk_IDUser_Destinatario; 
                    item.Fk_IDDoc = retData.Fk_IDDoc;
                    item.Titolo = retData.Titolo;
                    item.AttivitaIter = retData.AttivitaIter;
                    item.Fk_IDAttivitaIter = retData.Fk_IDAttivitaIter;
                    item.Scadenza = retData.Scadenza;
                    item.Urgenza = item.Urgenza; 
                }
            }            
        }//fM


        private void contMenu_Click(object sender, RoutedEventArgs e)
        {
            var lst = contMenu.PlacementTarget as ListView;
            var selDoc = lst.SelectedItem as Iters;
            if (selDoc == null) return;

            var comando = ((MenuItem)e.Source).Header.ToString().ToLower();
            switch (comando)
            {
                case "modifica":
                    var item = m_ItersList.Where(x => x.ID == selDoc.ID).FirstOrDefault();
                    updateIter(item);
                    break;
                case "download":

                    break;
                case "delete":

                    break;
                case "avvia iter":
                    CreaWFControl iter = new CreaWFControl(selDoc.ID, m_FileName);
                    getFrameContainer().Content = iter;
                    break;
                default:
                    break;
            }

        }

        //Salva l'iter in blocco
        private void btnSalvaIter_Click(object sender, RoutedEventArgs e)
        {
            if(string.IsNullOrEmpty(txtIDdoc.Text.Trim()) )
            {
                messaggia("Manca l'identificativo del documento !");return ; 
            }

            int idDoc=0;
            if(!int.TryParse(txtIDdoc.Text,out idDoc))
            {
                messaggia("Identificativo del documento errato !");return ; 
            }
            if(idDoc == 0)
            {
                messaggia("Identificativo del documento errato !");return ;  
            }

            if (GLOBALcontrols.UtenteDati == null)
            {
                messaggia(""); 
            }

            var iterManager = ItersManager.CreateItersManager(-1, idDoc, GLOBALcontrols.UtenteDati.UserId,
               GLOBALcontrols.UserName, "Titolo ", false, 0);

            var totUpdatati = 0;
              //totUpdatati = new QueryIters().updateItersManager(ref iterManager); 
            
            Iters iterNew = null;
            

            foreach (Iters item in lstIters.Items)
            {               
                try
                {                   
                    iterNew = Iters.CreateIters(item.ID, iterManager.ID, item.Titolo, item.Fk_IDDoc,
                      item.Fk_IDUser_Destinatario, item.Destinatario, item.Fk_IDAttivitaIter,
                      GLOBALcontrols.UtenteDati.UserId, item.IsTerminated);
                    iterNew.Messaggio = item.Messaggio; 

                    iterManager.Iters.Add(iterNew);
                }
                catch (Exception ex)
                {
                    messaggia("errore in creazione iter (aggiunta iter) : \r\n"+ ex.Message);return ;
                }

            }

            totUpdatati = new QueryIters().updateItersManager(ref iterManager); 


        }

        private void contMenulstWorkflows_Click(object sender, RoutedEventArgs e)
        {

        }//fM


    }//fC
}
